﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Caliburn.Micro;
using WinMote7.Helpers;
using System.Collections.ObjectModel;
using UPnPControllerServices;

namespace WinMote7.ViewModels
{
    public class PlayMediaViewModel : INotifyPropertyChangedEx
    {
        readonly INavigationService navigationService;

        private string mediaItemUri;

        private Guid serverId;

        public PlayMediaViewModel(INavigationService navigationService)
        {
            LoadingPanel = true;
            Renderers = new ObservableCollection<MediaRendererWrapper>();
            this.navigationService = navigationService;

            LoadParameters(navigationService);

            // load data
            LoadMediaRenderers();
        }

        private void LoadMediaRenderers()
        {
            UPnPMediaBrowserServiceClient client = new UPnPMediaBrowserServiceClient();
            client.GetAvailableMediaRenderersCompleted += new EventHandler<GetAvailableMediaRenderersCompletedEventArgs>(client_GetAvailableMediaRenderersCompleted);
            client.GetAvailableMediaRenderersAsync();
        }

        private void LoadParameters(INavigationService navigationService)
        {
            var queryString = QueryStringHelper.ParseQueryString(navigationService.Source.OriginalString);

            string mediaName = string.Empty;
            queryString.TryGetValue("MediaName", out mediaName);
            VideoTitle = HttpUtility.UrlDecode(mediaName);

            queryString.TryGetValue("serverId", out mediaName);
            serverId = new Guid(HttpUtility.UrlDecode(mediaName));

            queryString.TryGetValue("MediaUri", out mediaName);
            mediaItemUri = HttpUtility.UrlDecode(mediaName);
        }

        void client_GetAvailableMediaRenderersCompleted(object sender, GetAvailableMediaRenderersCompletedEventArgs e)
        {
            Renderers.Clear();

            foreach (MediaRenderer item in e.Result)
            {
                Renderers.Add(new MediaRendererWrapper()
                {
                    Description = item.Description,
                    FriendlyName = item.FriendlyName,
                    RendererId = item.RendererId,
                    IconSource = item.Description == "Windows Media Player Renderer" ? "/Resources/MediaPlayer.png" : "/Resources/UnknownTV.png"
                });
            }

            Renderers.Add(new MediaRendererWrapper()
                {
                    Description = "Windows Phone 7 Player",
                    FriendlyName = "This Phone",
                    RendererId = Guid.Empty,
                    IconSource = "/Resources/WP7Icon.png"
                });

            LoadingPanel = false;
            NotifyOfPropertyChange("LoadingPanel");
            NotifyOfPropertyChange("NoResultsFound");
        }

        public string VideoTitle
        {
            get;
            set;
        }

        public bool LoadingPanel
        {
            get;
            set;
        }

        public bool NoResultsFound
        {
            get
            {
                return Renderers.Count == 0;
            }
        }

        public ObservableCollection<MediaRendererWrapper> Renderers
        {
            get;
            set;
        }

        public void NotifyOfPropertyChange(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }

        public void PlayMedia(MediaRendererWrapper from)
        {
            if (from.RendererId != Guid.Empty)
            {
                UPnPMediaBrowserServiceClient client = new UPnPMediaBrowserServiceClient();
                client.PlayMediaAsync(mediaItemUri, serverId, from.RendererId);
            }

            #region test code

            navigationService.Navigate(new Uri(string.Format("/Views/PhonePlayer.xaml?MediaUri={0}&FileName={1}&RendererId={2}", HttpUtility.UrlEncode(mediaItemUri), HttpUtility.UrlEncode(VideoTitle), HttpUtility.UrlEncode(from.RendererId.ToString())), UriKind.RelativeOrAbsolute));

            #endregion
        }

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
    }

    public class MediaRendererWrapper
    {
        public string IconSource { get; set; }

        public string FriendlyName { get; set; }

        public string Description { get; set; }

        public Guid RendererId { get; set; }
    }
}
